import F_login from "@/components/web/f_login.vue";
import {h, createApp, ref, watch, type App} from "vue";
import { defineComponent } from "vue";

const visible = ref<boolean | undefined>(undefined);

export function showLogin(options?: { isReload: boolean, to?: string }) {

    let app: App<Element> | null = null; // 保存 app 实例
    let div: HTMLDivElement | null = null; // 保存挂载的 DOM 节点

    if (visible.value === undefined) {
        const component = defineComponent({
            render: () => {
                return h(F_login, {
                    visible: visible.value as boolean,
                    isReload: options?.isReload,
                    to: options?.to,
                    "onUpdate:visible": (newValue) => {
                        visible.value = newValue;
                    },
                });
            },
        });

        // 生成app
        app = createApp(component);

        // 挂载
        div = document.createElement("div");
        app.mount(div);

        document.body.append(div);

        // 监听 visible 的变化，当变为 false 时卸载组件
        watch(visible, (newVal) => {
            if (newVal === false) {
                if (app && div) {
                    app.unmount(); // 卸载 Vue 应用
                    document.body.removeChild(div); // 从 DOM 中移除挂载点
                    app = null; // 清理引用
                    div = null; // 清理引用
                    visible.value = undefined; // 重置 visible 状态
                }
            }
        });
    }

    visible.value = true;
}
